package com.bwie.auth.service.impl;

import cn.hutool.core.util.IdUtil;
import com.bwie.auth.remote.SystemRemote;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.Constants;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserReq;
import com.bwie.common.exception.BizException;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className: AuthServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author:
 * @date:
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private SystemRemote systemRemote;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String login(UserReq userReq) {
        //验证码比对
        Boolean b = redisTemplate.hasKey(userReq.getCode());
        if(!b){
            throw new BizException("验证码过期或者输入错误");
        }

        //数据库查找
        Result<User> byPhoneAndPassword = systemRemote.findByPhoneAndPassword(userReq);
        if(byPhoneAndPassword.getCode()== Constants.ERROR){
            throw new BizException("服务器异常");
        }
        User login = byPhoneAndPassword.getData();
        if(ObjectUtils.isEmpty(login)){
            throw new BizException("手机号或者密码错误");
        }
        //生成验证码
        String userKey = IdUtil.fastSimpleUUID();
        Map<String, Object> map = new HashMap<String, Object>() {{
            put(JwtConstants.USER_KEY, userKey);
        }};
        String token = JwtUtils.createToken(map);
        //登录人信息缓存到数据库
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey,login,15, TimeUnit.MINUTES);

        return token;
    }
}
